package com.service.impl;

import com.dao.ICartdao;
import com.dao.impl.Cartdaoimpl;
import com.entity.Cart;
import com.entity.Phone;
import com.entity.User;
import com.service.ICartService;
import com.service.IPhoneService;
import com.service.IUserService;
import com.utlils.DBUtlils;

import java.util.*;

public class CartServiceimpl implements ICartService {
    IPhoneService service=new PhoneServiceimpl();
    ICartdao dao=new Cartdaoimpl();
    IUserService userService=new UserServiceimpl();
    @Override
    public Integer inserCart(Integer uid, Integer pid) {
        Integer integer=null;
        //判断是否存在重复的订单
//        Boolean save = dao.findByUidPidCart(uid, pid);
//        if(save){
            //存在则将value+1
            Integer value = service.findPValue(uid);
            value=value+1;
            service.UpDatePValue(value,uid);

            //否则创建新的购物车订单
            Phone p = service.findById(pid);
            Cart cart =new Cart();
            cart.setUid(uid);
            cart.setPid(pid);
            cart.setPhone(p);
            cart.setTotal(1);
            cart.setValue(1);
            //创建购物车
            integer = dao.inserCart(cart);

        return integer;
    }

    @Override
    public List<Phone> findCart(Integer uid) {
        List<Integer> cart = dao.findByCart(uid);
        List<Phone> list = new ArrayList<>();
        for (Integer in : cart) {
            Phone p = service.findById(in);
            list.add(p);
        }
      return list;
    }


    @Override
    public List<Phone> findByNameCart(String name) {
        User u = userService.findByName(name);
        List<Phone> phones=new ArrayList<>();
        int uid = u.getId();
        List<Integer> integers = dao.findByCart(uid);
        for (int in:integers) {
            if(in!=0){
                phones.add(service.findById(in));
            }
        }
        return phones;
    }

    @Override
    public Integer DeleteCart(String name, Integer pid) {
        User us = userService.findByName(name);
        int uid = us.getId();
        Integer integer = dao.DleProduct(uid, pid);

        return integer;
    }

    @Override
    public Integer UpDateState(Integer value, Integer uid) {
        Integer integer = dao.UpDateState(uid, value);
        return integer;
    }


}
